package org.example.service;

import java.io.*;
import java.net.Socket;

public class RpcService {
    private Socket clientSocket;
    private DataOutputStream out;
    private DataInputStream in;

    public void startConnection(String ip, int port) throws IOException {
        clientSocket = new Socket(ip, port);
        out = new DataOutputStream(clientSocket.getOutputStream());
        in = new DataInputStream(clientSocket.getInputStream());
    }

    public byte[] sendMessage(byte[] requestBytes) throws IOException {
        out.write(requestBytes);
        out.flush();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int count = in.read(buffer);
        bos.write(buffer, 0, count);

        byte[] res = null;
        res = bos.toByteArray();
        return res;
    }

    public void stopConnection() throws IOException {
        in.close();
        out.close();
        clientSocket.close();
    }
}
